package fdq.servlet;

import com.alibaba.fastjson.JSON;
import fdq.entity.Animal;
import fdq.entity.AnimalSet;
import fdq.entity.Feature;
import fdq.service.MainService;
import fdq.service.MainServiceImp;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/featureServlet")
public class FeatureServlet extends HttpServlet {

    //特征集
    static ArrayList<Feature>  featureList = new ArrayList<>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("FeatureServlet被访问");
        String featureOffer = req.getParameter("featureOffer");
        int featureOfferInt = Integer.parseInt(featureOffer);
        System.out.println(featureOfferInt);

        MainService mainService = new MainServiceImp();

        //构建特征集


        featureList.add(new Feature(featureOfferInt));
        //扩展特征集
        featureList = mainService.expandFeatures(featureList);

        System.out.println("application中的特征有：");
        for(Feature f : featureList){
            System.out.println(f.getFeature());
        }
        System.out.println("---------------------------------");

        //构建可能的动物集
        AnimalSet animalSet = mainService.createAnimalSet(featureList);

        //返回可能动物集中的全部特征
        ArrayList<Feature> animalFeatureList = mainService.selectFeaturesFromSet(animalSet);



        //特征集与全部动物进行比对
        AnimalSet allAnimal = mainService.getAllAnimal();

        Animal animal = allAnimal.isCorrespond(featureList);



        //可推理出的动物的特征发送给前端
        resp.setCharacterEncoding("utf-8");
        Map<String,Object> map=new HashMap<>();
        map.put("animalFeatureList",animalFeatureList);
        map.put("features",featureList);
        map.put("animal",animal);
        String json= JSON.toJSONString(map);
        PrintWriter pw =resp.getWriter();
        pw.print(json);


    }
}
